/*
 * 文件名：OrderInfoService.java
 * 版权：Copyright by www.huawei.com
 * 描述：
 * 修改人：zhangshaohua
 * 修改时间：2016年4月25日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.service.mall.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.constants.PushConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.CommonConfig;
import com.zcsy.manage.model.mall.GoodsSpecification;
import com.zcsy.manage.model.mall.GoodsSpecificationAttr;
import com.zcsy.manage.model.mall.IntegralRecord;
import com.zcsy.manage.model.mall.OrderDetailInfo;
import com.zcsy.manage.model.mall.OrderInfo;
import com.zcsy.manage.model.mall.OrderMoney;
import com.zcsy.manage.model.mall.ShoppingCart;
import com.zcsy.manage.model.pay.alipay.AliPayResult;
import com.zcsy.manage.model.pay.weixin.PayOrderResultResponse;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.base.CommonConfigDao;
import com.zcsy.manage.persistence.mall.GoodsSpecificationAttrDao;
import com.zcsy.manage.persistence.mall.GoodsSpecificationDao;
import com.zcsy.manage.persistence.mall.IntegralRecordDao;
import com.zcsy.manage.persistence.mall.OrderDetailInfoDao;
import com.zcsy.manage.persistence.mall.OrderInfoDao;
import com.zcsy.manage.persistence.system.RoleCellDao;
import com.zcsy.manage.persistence.system.RoleMenuDao;
import com.zcsy.manage.persistence.system.UserDao;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IOrderInfoService;
import com.zcsy.manage.service.push.IPushService;
import com.zcsy.manage.service.quartz.ITimerTaskService;
import com.zcsy.manage.service.quartz.impl.TimerTaskServiceImpl;
import com.zcsy.manage.service.wxpay.service.WxPayResult;

/**
 * 
 * @Title: OrderInfoService.java
 * @Package： com.zcsy.manage.service.mall.impl 
 * @Description: 订单服务实现类
 * @author zhangsh zsh3384027@gmail.com
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 * @date 2016年4月25日
 * @version 1.0
 * @see JDK1.8.0_45
 * @since
 */
@Service
public class OrderInfoService implements IOrderInfoService{
	
	@Autowired
	private OrderInfoDao orderInfoDao;
	
	@Autowired
    private OrderDetailInfoDao orderDetailDao;
	
	@Autowired
	private RoleCellDao roleCellDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired 
	RoleMenuDao roleMenuDao;
	
	@Autowired 
    private IGoodsInfoService goodsInfoService;
	
	@Autowired 
	private GoodsSpecificationDao speciDao;
	
	@Autowired 
	private GoodsSpecificationAttrDao goodsSpecificationAttrDao;
	
	@Autowired 
	private OrderDetailInfoDao orderDetailInfoDao;
	
    @Autowired
    private IPushService pushService;

    @Autowired
    private IntegralRecordDao integralRecordDao;

    @Autowired
    private CommonConfigDao commonConfigDao;
    
    @Autowired
    private ITimerTaskService timeTaskService;
	
	
	@Override
	public int insert(OrderInfo orderInfo) {
		return orderInfoDao.insert(orderInfo);
	}

	@Override
	public int update(OrderInfo orderInf) {
		OrderInfo oldInfo = orderInfoDao.selectByPrimaryId(orderInf.getId());
		
		oldInfo.setState(orderInf.getState());
		oldInfo.setSendTime(orderInf.getSendTime());
		oldInfo.setSendAccount(orderInf.getSendAccount());
		oldInfo.setRefundSuccessTime(orderInf.getRefundSuccessTime());
		oldInfo.setRefundSuccessAccount(orderInf.getRefundSuccessAccount());
		oldInfo.setReturnSuccessTime(orderInf.getReturnSuccessTime());
		oldInfo.setReturnSuccessAccount(orderInf.getReturnSuccessAccount());
		oldInfo.setReason(orderInf.getReason());
		oldInfo.setConfirmTime(orderInf.getConfirmTime());
		oldInfo.setPayTime(orderInf.getPayTime());
		oldInfo.setCancelTime(orderInf.getCancelTime());
	    oldInfo.setCancelType(orderInf.getCancelType());
	    oldInfo.setCancelAccount(orderInf.getCancelAccount());
	    oldInfo.setRefundRequestTime(orderInf.getRefundRequestTime());
	    
		return orderInfoDao.update(oldInfo);
	}
	
	@Override
	public int updateByParentOrder(OrderInfo orderInf) {
		return orderInfoDao.updateByParentOrder(orderInf);
	}

	@Override
	public OrderInfo selectOrderByPrimaryKey(String id) {
		return orderInfoDao.selectOrderByPrimaryKey(id);
	}
	
	@Override
	public 
	OrderInfo selectByOrderNumber(String no) {
		return orderInfoDao.selectByOrderNumber(no);
	}

	@Override
	public int deleteByPrimaryKey(String id) {
		return orderInfoDao.deleteByPrimaryKey(id);
	}

	@Override
	public List<OrderInfo> selectByKeyword(OrderInfo orderInf) {
		return orderInfoDao.selectByKeyword(orderInf);
	}
	
	@Override
	public List<OrderInfo> selectSellerOrderListByKeyword(OrderInfo keyword) {
		return orderInfoDao.selectSellerOrderListByKeyword(keyword);
	}
	
    @Override
    public List<OrderDetailInfo> getOrderDetailByOrderId(String orderId) {
        return orderDetailInfoDao.getOrderDetailByOrderId(orderId);
    }

	@Override
	public int updateOrderStateByMap(String id, int state, String userAccount) {
		Map map = new HashMap<String, Object>();
		map.put("id", id);
		map.put("state", state);
		map.put("userAccount", userAccount);
		
		OrderInfo orderInfo =  orderInfoDao.selectByPrimaryId(id);
		switch(state){
			case Constants.ORDER_CANCEL :
			    // 更新库存和订单状态
                cancelOrder(id);
                
				 // 订单取消，推送给业主app
		        pushService.pushOwnerMsg(id, PushConstants.PUSH_TYPE_OWNER_ORDER);
		        break;
		        
			case Constants.ORDER_UNSEND ://商家确认，需要配送，转为待发货
				Date sellerConfirmDate = new Date();
				orderInfo.setState(Constants.ORDER_UNSEND);
				orderInfo.setSureTime(sellerConfirmDate);
				
				//待配送订单，推送给配送app
				pushService.pushDistributionMsg(id,Constants.PUSH_TYPE_RUSH);
				
				//定时器，5分钟后无配送人员接单，推送给派单管理员
				timeTaskService.orderTimeTask(TimerTaskServiceImpl.TASK_UNSEND, id);
				break;
				
			case Constants.ORDER_DISTRIBUTION_ING :
				 Date sendGoodsTime = new Date();
				 orderInfo.setState(Constants.ORDER_DISTRIBUTION_ING);
				 orderInfo.setSendTime(sendGoodsTime);
				 orderInfo.setSendAccount(userAccount);
				 
				// 订单配送中，推送给业主app
		        pushService.pushOwnerMsg(id, PushConstants.PUSH_TYPE_OWNER_ORDER);
		        break;
			case Constants.ORDER_REFUND_CONFIRMED : // 退款确认
				 Date refundConfirmTime = new Date();
				 orderInfo.setState(Constants.ORDER_REFUND_CONFIRMED);
				 orderInfo.setRefundConfirmTime(refundConfirmTime);;
				 orderInfo.setRefundConfirmAccount(userAccount);;
				
			    // 更新库存信息
		        List<OrderDetailInfo> refundList = orderDetailInfoDao.getOrderDetailByPrarentId(id);
		        goodsInfoService.updateGoodsStockAndSalesCancel(refundList);
		        break;
			case Constants.ORDER_UNCONFORM : // 退款拒绝，改为待商家确认
				 orderInfo.setState(Constants.ORDER_UNCONFORM);
				 break;
				 
			case Constants.ORDER_RETURN_CONFIRMED : // 退货确认
				 Date returnConfirmTime = new Date();
				 orderInfo.setState(Constants.ORDER_RETURN_CONFIRMED);
				 orderInfo.setReturnConfirmTime(returnConfirmTime);;
				 orderInfo.setReturnConfirmAccount(userAccount);;
				 
                // 更新库存信息
                List<OrderDetailInfo> refurnList = orderDetailInfoDao.getOrderDetailByPrarentId(id);
                goodsInfoService.updateGoodsStockAndSalesCancel(refurnList);
                break;
                
			case Constants.ORDER_DONE : // 退货拒绝，改为已完成
				 orderInfo.setState(Constants.ORDER_DONE);
				 break;
				 
			case Constants.ORDER_UNSERVICE : // 商家确认，无需配送订单改为待消费
				Date sellerConfirmtime = new Date();
				orderInfo.setState(Constants.ORDER_UNSERVICE);
				orderInfo.setSureTime(sellerConfirmtime);
				break;
		        
			default :break;
		}
		
		return orderInfoDao.update(orderInfo);
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.zcsy.manage.distribution.service.mall.CIOrderInfoService#selectAccountsFromOrderByRoles(java.util.List, java.util.List)
	 */
	@Override
	public List<String> selectAccountsFromOrderByRoles(String orderId,
			List<String> menuValues) {
		// TODO Auto-generated method stub
		//通过订单id查询小区id
		List<String> orderList = new ArrayList<String>();
		orderList.add(orderId);
		System.out.println(orderList.get(0));
		List<String> cellList = orderInfoDao.selectByOrderId(orderList);
		//通过小区id查找小区有配送的权限的角色id
		List<String> rolelList = roleCellDao.selectRolesByCellId(cellList);
		//通过权限id查找有配送或指派或报表角色id
		List<String> roleList2 = roleMenuDao.selectMenuIdByRoleId(menuValues);
		
		List newRolelList = new ArrayList();
		
	    for (String list1 : rolelList) {
			for (String list2 : roleList2) {
				if (list1.equals(list2)) {
					newRolelList.add(list1);
				}
			}
		}
		//通过角色id查找loginname
	    if(null != newRolelList && newRolelList.size() > 0) {
	        List<String> loginnameList = userDao.selectLoginNameByRole(newRolelList);
	        return loginnameList;
	    } else {
	        return null;
	    }
	}

	@Override
	public List<OrderInfo> selectByStateAndUserAccount(Integer state,Integer reviewState,
			String userAccount) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("state", state);
		map.put("reviewState", reviewState);
		map.put("userAccount", userAccount);
		return orderInfoDao.selectByStateAndUserAccount(map);
	}
	
	@Override
	public List<OrderInfo> selectOrderInfoAll(Integer state,
			String userAccount) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("state", state);
		map.put("userAccount", userAccount);
		return orderInfoDao.selectOrderInfoAll(map);
	}
	
	@Override
	public List<OrderInfo> selectOrderInfoMyCurrentCell(
			String userAccount, String cellId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userAccount", userAccount);
		map.put("cellId", cellId);
		return orderInfoDao.selectOrderInfoMyCurrentCell(map);
	}


    @Override
    public OrderMoney setOrderCost(List<ShoppingCart> detailList,User user) {
         OrderMoney money = new OrderMoney();
        money.setMainDiscountWay(-1);
        money.setSuccess(true);
        money.setMoney(new BigDecimal(0));
        money.setAmount(0);
        String goodName = "";
        
        for(ShoppingCart detail : detailList){
            //判断商品是否下架，如果商品已下架，则不允许购买
            if(detail.getGoodsState() == Constants.GOODS_SALE){
                //如果规格id不为null，从规格表中获取商品单价，否则从商品表获取商品单价
                if(detail.getSpecificationId() != null){
                    //判断购买的商品的规格是否存在，如果不存在，不允许购买
                    GoodsSpecification specification = speciDao.getGoodsSpecificationById(detail.getSpecificationId());
                    if(specification != null){
                        //判断规格的存储量，如果等于0不允许购买
                        if(specification.getStock() < detail.getAmount()){
                            if("".equals(goodName)){
                                goodName = detail.getGoodsName();
                            }else{
                                goodName = goodName + "," + detail.getGoodsName();
                            }
                            money.setMsg("你所购买的"+ goodName +"商品库存不足");
                            money.setSuccess(false);
                            
                            return money;
                        }else{
                            BigDecimal totalPrice ;
                            BigDecimal amount = new BigDecimal(detail.getAmount());
                            
                            totalPrice = specification.getPrice().multiply(amount);
                            money.setMoney(money.getMoney().add(totalPrice));
                            money.setAmount(money.getAmount() + detail.getAmount().intValue());
                        }
                    }else{
                        if("".equals(goodName)){
                            goodName = detail.getGoodsName();
                        }else{
                            goodName = goodName + "," + detail.getGoodsName();
                        }
                        money.setMsg("你所购买的"+ goodName +"商品信息已变更无法购买");
                        money.setSuccess(false);
                        
                        return money;
                    }
                }else{
                    if(detail.getStock() < detail.getAmount()){
                        if("".equals(goodName)){
                            goodName = detail.getGoodsName();
                        }else{
                            goodName = goodName + "," + detail.getGoodsName();
                        }
                        money.setMsg("你所购买的"+ goodName +"商品信息库存不足");
                        money.setSuccess(false);
                        
                        return money;
                    }else{
                        BigDecimal totalPrice ;
                        BigDecimal amount = new BigDecimal(detail.getAmount());
                        
                        totalPrice = detail.getPrice().multiply(amount);
                        money.setMoney(money.getMoney().add(totalPrice));
                        money.setAmount(money.getAmount() + detail.getAmount().intValue());
                    }
                }
            }else{
                if(goodName == ""){
                    goodName = detail.getGoodsName();
                }else{
                    goodName = goodName + "," + detail.getGoodsName();
                }
                money.setMsg("你所购买的"+ goodName +"商品已下架");
                money.setSuccess(false);
                
                return money;
            }
        }
        
        return money;
    }
    
    @Override
    public Integer getShopOrderSum(Map<String, Object> map){
    	return orderInfoDao.getShopOrderSum(map);
    }
    
	@Override
	public int saveOrderDetail(OrderDetailInfo recore) {
		String specification = "";
        if(recore.getSpecificationId() != null){
            Map map = new HashMap<String, Object>();
            map.put("goodsId", recore.getGoodsId());
            map.put("specificationId", recore.getSpecificationId());
            List<GoodsSpecificationAttr> list = goodsSpecificationAttrDao.getGoodsSpecAttrBySpecId(map);
            if(list != null){
            	StringBuffer buffer = new StringBuffer();
            	for(GoodsSpecificationAttr item : list){
            		if(StringUtils.isNotEmpty(item.getAttrValue())){
            			buffer.append(item.getAttrValue() + "，");
            		}else if(StringUtils.isNotEmpty(item.getAttributeValue())){
            			buffer.append(item.getAttributeValue() + "，");
            		}
            	}
            	
            	if(buffer.length() > 0){
            		specification = buffer.substring(0, buffer.length() - 1).toString();
            	}
            }
        }
        recore.setSpecification(specification);
        recore.setSendTime(new Date());
        return orderDetailInfoDao.insert(recore);
	}
	
	@Override
	public List<OrderInfo> selectByShopIdAndState(String shopId, Integer state){
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("shopId", shopId);
        map.put("state", state);
		return orderInfoDao.selectByShopIdAndState(map);
	}
	
	@Override
	public List<OrderInfo> selectOrderListByShopIdStates(String shopId, String states){
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("shopId", shopId);
        map.put("states", null != states ? states.split(",") : null);
		return orderInfoDao.selectOrderListByShopIdStates(map);
	}
	
	@Override
	public List<OrderInfo> selectAfterSaleByShopId(String shopId){
		return orderInfoDao.selectAfterSaleByShopId(shopId);
	}
	
	@Override
    public OrderInfo selectByPrimaryId(String id){
        return orderInfoDao.selectByPrimaryId(id);
    }
	
	@Override
	public List<OrderInfo> getOrderAndGoodsInfo(OrderInfo orderInfo) {
	    return orderInfoDao.getOrderAndGoodsInfo(orderInfo);
	}
	
	@Override
	public List<OrderInfo> getOrderByKeyWords(OrderInfo orderInfo) {
	    return orderInfoDao.getOrderByKeyWords(orderInfo);
	}

	@Override
	public List<OrderInfo> selectOrderInfoByCellIdStateUserAccount(String cellId, String userAccount, String states) {
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("cellId", cellId);
        map.put("userAccount", userAccount);
        map.put("states", null != states ? states.split(",") : null);
		return orderInfoDao.selectOrderInfoByCellIdStateUserAccount(map);
	}
	
	@Override
    public OrderInfo selectOrderInfoAllById(String id){
        return orderInfoDao.selectOrderInfoAllById(id);
    }
	
	@Override
	public List<OrderInfo> selectOrderInfoList(String cellId, String userAccount, String states) {
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("cellId", cellId);
        map.put("userAccount", userAccount);
        map.put("states", StringUtil.isEmptyString(states) ? null : states);
        map.put("ids", StringUtil.isEmptyString(states) ? null : states.split(","));
		return orderInfoDao.selectOrderInfoList(map);
	}

	public List<OrderInfo> selectOrderAllInfoList(String cellId, String userAccount){
	    Map<String, Object> map = new HashMap<String, Object>();
        map.put("cellId", cellId);
        map.put("userAccount", userAccount);
        return orderInfoDao.selectAllOrderInfoList(map);
	}
	
    @Override
    public void payOrder(String orderNo, Object obj) {
        OrderInfo orderInfo = orderInfoDao.selectByOrderNumber(orderNo);
        if(orderInfo.getState() != Constants.ORDER_UNPAID){
        	return;
        }
        
        if(orderInfo.getOrderLevel() == Constants.ORDER_LEVEL_ONE){
        	orderInfo.setState(Constants.ORDER_DONE);
        }else{
        	//子订单状态取决于对应属性，积分、秒杀兑换订单无需确认
        	if(orderInfo.getType() != null && orderInfo.getType().intValue() != Constants.GOODS_TYPE_CARDS
        			&& orderInfo.getType().intValue() != Constants.GOODS_TYPE_SECKILL && orderInfo.getIsNeedConfirm() == Constants.IS_BYSELF_Y){
        		orderInfo.setState(Constants.ORDER_UNCONFORM);//待确认
        	}else{
        		//支持配送且未选自提
        		if(orderInfo.getDistributionType() == Constants.IS_HAS_DISN_Y
        				&& orderInfo.getIsBySelf() == Constants.IS_BYSELF_N){
        			orderInfo.setState(Constants.ORDER_UNSEND);//待发货
        		}else{
        			orderInfo.setState(Constants.ORDER_UNSERVICE);//待消费
        		}
        	}
        }
        orderInfo.setPayTime(new Date());
        if(obj instanceof PayOrderResultResponse) {
        	//微信网页扫码
        	PayOrderResultResponse result = (PayOrderResultResponse)obj;
            orderInfo.setPayType(Constants.PAY_TYPE_WX);
            orderInfo.setPaySystem(Constants.PAY_SYSTEM_WEB);
            orderInfo.setExternalRespCode(result.getResult_code());
            orderInfo.setExternalTradeNo(result.getOut_trade_no());
        	//微信支付返回的金额是以分为单位，所以要除以100
            orderInfo.setTotalFee(
            		new BigDecimal(result.getTotal_fee()).divide(new BigDecimal(100)));
        }else if(obj instanceof AliPayResult){
        	//支付宝
        	AliPayResult result = (AliPayResult)obj;
        	orderInfo.setPayType(Constants.PAY_TYPE_ALI);
            orderInfo.setPaySystem(result.getPaySystem());
            orderInfo.setExternalRespCode(result.getExternal_resp_code());
            orderInfo.setExternalTradeNo(result.getExternal_trade_no());
            orderInfo.setTotalFee(result.getTotal_fee());
        }else if(obj instanceof WxPayResult){
        	//微信app支付
        	WxPayResult result = (WxPayResult)obj;
        	orderInfo.setPayType(Constants.PAY_TYPE_WX);
            orderInfo.setPaySystem(result.getPaySystem());
            orderInfo.setExternalRespCode(result.getResultCode());
            orderInfo.setExternalTradeNo(result.getOutTradeNo());
            //微信支付返回的金额是以分为单位，所以要除以100
            orderInfo.setTotalFee(
            		new BigDecimal(result.getTotalFee()).divide(new BigDecimal(100)));
        }
        orderInfoDao.update(orderInfo);
        
        //更新子订单状态
        if(orderInfo.getOrderLevel() == Constants.ORDER_LEVEL_ONE){
        	List<OrderInfo> itemList = orderInfoDao.selectOrderByParentId(orderInfo.getId());
            for(OrderInfo order : itemList){
            	//子订单状态取决于对应属性，积分兑换订单无需确认
            	if(order.getType() != null && order.getType().intValue() != Constants.GOODS_TYPE_CARDS
            			&& order.getIsNeedConfirm() == Constants.IS_BYSELF_Y){
            		order.setState(Constants.ORDER_UNCONFORM);//待确认
            	}else{
            		//支持配送且未选自提
            		if(order.getDistributionType() == Constants.IS_HAS_DISN_Y
            				&& order.getIsBySelf() == Constants.IS_BYSELF_N){
            			order.setState(Constants.ORDER_UNSEND);//待发货
            		}else{
            			order.setState(Constants.ORDER_UNSERVICE);//待消费
            		}
            	}
            	
            	
                
                order.setPayTime(new Date());
                if(obj instanceof PayOrderResultResponse) {
                	//微信网页扫码
                	PayOrderResultResponse result = (PayOrderResultResponse)obj;
                    order.setPayType(Constants.PAY_TYPE_WX);
                    order.setPaySystem(Constants.PAY_SYSTEM_WEB);
                    order.setExternalRespCode(result.getResult_code());
                	order.setExternalTradeNo(result.getOut_trade_no());
                	//微信支付返回的金额是以分为单位，所以要除以100
                	order.setTotalFee(
                    		new BigDecimal(result.getTotal_fee()).divide(new BigDecimal(100)));
                }else if(obj instanceof AliPayResult){
                	//支付宝
                	AliPayResult result = (AliPayResult)obj;
                	order.setPayType(Constants.PAY_TYPE_ALI);
                	order.setPaySystem(result.getPaySystem());
                	order.setExternalRespCode(result.getExternal_resp_code());
                	order.setExternalTradeNo(result.getExternal_trade_no());
                	order.setTotalFee(result.getTotal_fee());
                }else if(obj instanceof WxPayResult){
                	//微信app支付
                	WxPayResult result = (WxPayResult)obj;
                	order.setPayType(Constants.PAY_TYPE_WX);
                	order.setPaySystem(result.getPaySystem());
                	order.setExternalRespCode(result.getResultCode());
                	order.setExternalTradeNo(result.getOutTradeNo());
                	//微信支付返回的金额是以分为单位，所以要除以100
                	order.setTotalFee(
                    		new BigDecimal(result.getTotalFee()).divide(new BigDecimal(100)));
                }
                orderInfoDao.update(order);
            }
        }
        /*********************************************************************************
         * 超市、水果店购物等商户的购物，按照交易金额的个位数取整计算,积分订单扣积分，正常订单加积分，秒杀订单不管*
         *********************************************************************************/
        
        // 获取当前登陆的用户的信息
        User user = userDao.selectByLoginName(orderInfo.getUserAccount());
        // 每日积分上限
        CommonConfig commonConfig = commonConfigDao.getByName("mall_integral_config");
        // 用户可获得的积分
        Integer integralOrder = orderInfo.getTotalPrice().intValue();
        IntegralRecord integralRecord = new IntegralRecord();
        
        // 如果订单是正常订单，才加积分
        if (orderInfo.getType() == Constants.GOODS_TYPE_NORMAL) {
            
            // 获取当前用户当天的积分变更记录
            List<IntegralRecord> integralRecordList = integralRecordDao
                    .selectRecordByUserAccount(user.getLoginname());
            // 定义当前用户当天积分变动之和
            Integer soFarIntegralSum = 0;
            // 求当前用户当天积分变动之和
            for (int i = 0; i < integralRecordList.size(); i++) {
                if(integralRecordList.get(i).getChange() > 0) {
                    soFarIntegralSum += integralRecordList.get(i).getChange();
                }
            }
            String integraLabel = "超市、水果店购物等商户的购物获得积分";
            
            // 判断可加的积分不为零才加积分
            if (Constants.STATE_DISABLED != integralOrder) {
                if (commonConfig != null && commonConfig.getValue().matches("[0-9]+")) {
                    // 用户当天可加积分之和的上限
                    Integer maxValuePerDay = Integer.valueOf(commonConfig.getValue());
                    
                    // 用户当天可加积分
                    int available = maxValuePerDay - soFarIntegralSum;
                    // 本次购物所加积分
                    int addIntegral = available < integralOrder ? available : integralOrder;
                    if (addIntegral > 0) {
                        user.setIntegral(user.getIntegral() + addIntegral);
                        userDao.updateByPrimaryKeySelective(user);

                        // 插入积分变更信息
                        integralRecord.setId(UniqueNumberUtils.get18UniqueNumber());
                        integralRecord.setChange(addIntegral);
                        integralRecord.setRecordTime(new Date());
                        integralRecord.setUserAccount(user.getLoginname());
                        integralRecord.setDescription(integraLabel);

                        integralRecordDao.insert(integralRecord);
                    }
                }
            } 
        } else if (orderInfo.getType() == Constants.GOODS_TYPE_CARDS) {// 积分订单
            if (user.getIntegral() > orderInfo.getCostIntegral()) { // 用户拥有的积分要大于应扣除的积分
                user.setIntegral(user.getIntegral() - orderInfo.getCostIntegral());
                userDao.updateByPrimaryKeySelective(user);

                // 插入积分变更信息
                integralRecord.setId(UniqueNumberUtils.get18UniqueNumber());
                integralRecord.setChange(-orderInfo.getCostIntegral());
                integralRecord.setRecordTime(new Date());
                integralRecord.setUserAccount(user.getLoginname());
                integralRecord.setDescription("扣除购买积分商品积分");

                integralRecordDao.insert(integralRecord);
            }
        }

        // 推送给商户app
        pushService.pushShopMsg(orderInfo.getId());
    }

    @Override
    public List<OrderInfo> selectByKeywordCommand(OrderInfo orderInf) {
        return orderInfoDao.selectByKeywordCommand(orderInf);
    }

    @Override
    public List<OrderInfo> selectCompletedOrder(String shopId) {
        return orderInfoDao.selectCompletedOrder(shopId);
    }

    @Override
    public List<OrderInfo> selectCanceledOrder(String shopId) {
        return orderInfoDao.selectCanceledOrder(shopId);
    }
    
    @Override
    public List<OrderInfo> selectOrderByParentId(String parentId) {
        return orderInfoDao.selectOrderByParentId(parentId);
    }

    @Override
    public List<OrderInfo> searchCompletedOrderByTime(String beginDate,String endDate,String shopId) {
        Map m = new HashMap();
        m.put("beginDate", beginDate);
        m.put("endDate", endDate);
        m.put("shopId", shopId);
        return orderInfoDao.searchCompletedOrderByTime(m);
    }

    @Override
    public List<OrderInfo> searchCanceledOrderByTime(String beginDate,String endDate,String shopId) {
        Map m = new HashMap();
        m.put("beginDate", beginDate);
        m.put("endDate", endDate);
        m.put("shopId", shopId);
        return orderInfoDao.searchCanceledOrderByTime(m);
    }

    @Override
    public List<OrderInfo> searchCompletedOrderByMonth(Integer secType,String beginDate, String endDate,String shopId) {
        Map m = new HashMap();
        m.put("secType", secType);
        m.put("beginDate", beginDate);
        m.put("endDate", endDate);
        m.put("shopId", shopId);
        return orderInfoDao.searchCompletedOrderByMonth(m);
    }

    @Override
    public List<OrderInfo> searchCanceledOrderByMonth(Integer secType,String beginDate, String endDate,String shopId) {
        Map m = new HashMap();
        m.put("secType", secType);
        m.put("beginDate", beginDate);
        m.put("endDate", endDate);
        m.put("shopId", shopId);
        return orderInfoDao.searchCanceledOrderByMonth(m);
    }
    
    @Override
    public int updateStateBeRefundAll() {
        // 更新库存
        List<OrderDetailInfo> orderList = orderDetailDao.getRefundOrderDetail();
        goodsInfoService.updateGoodsStockAndSalesCancel(orderList);
        
        return orderInfoDao.updateStateBeRefundAll();
    }
    
    @Override
    public int updateStateBeenSenddAll() {
        return orderInfoDao.updateStateBeenSenddAll();
    }

    @Override
    public void cancelOrder(String orderId) {
        
        // 更新订单状态
        OrderInfo orderInfo = orderInfoDao.selectByPrimaryId(orderId);
        orderInfo.setState(Constants.ORDER_CANCEL);
        orderInfo.setCancelTime(new Date());
        orderInfo.setCancelAccount(orderInfo.getUserAccount());
        orderInfoDao.update(orderInfo);
        
        if(orderInfo.getOrderLevel() == Constants.ORDER_LEVEL_ONE){
            List<OrderInfo> itemList = orderInfoDao.selectOrderByParentId(orderInfo.getId());
            for(OrderInfo order : itemList){
                order.setState(Constants.ORDER_CANCEL);
                order.setCancelTime(new Date());
                orderInfoDao.update(order);
            }
        } 
        // 更新库存信息
        List<OrderDetailInfo> detailList = orderDetailInfoDao.getOrderDetailByPrarentId(orderId);
        goodsInfoService.updateGoodsStockAndSalesCancel(detailList);
    }

}
